const { homeworkApi } = require('../../../utils/api');

Page({
  data: {
    homeworkList: [],
    filteredHomework: [],
    loading: false,
    error: null,
    searchKeyword: '',
    currentFilter: 'all',
    currentUserId: 1 // 这里应该从用户登录信息中获取
  },

  onLoad() {
    this.loadHomework();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadHomework();
  },

  // 加载作业列表
  async loadHomework() {
    console.log('开始加载作业列表...');
    this.setData({ loading: true, error: null });
    
    try {
      console.log('调用 homeworkApi.getAllHomework()...');
      const homeworkList = await homeworkApi.getAllHomework();
      console.log('获取作业列表成功:', homeworkList);
      console.log('作业列表类型:', typeof homeworkList);
      console.log('作业列表长度:', homeworkList ? homeworkList.length : 'undefined');
      
      // 检查返回的数据
      if (!homeworkList) {
        throw new Error('作业列表为空');
      }
      
      if (!Array.isArray(homeworkList)) {
        console.error('作业列表不是数组:', homeworkList);
        throw new Error('作业列表格式错误');
      }
      
      // 处理作业数据，添加格式化时间等
      const processedHomework = homeworkList.map(homework => {
        console.log('处理作业数据:', homework);
        return {
          ...homework,
          formattedTime: this.formatTime(homework.createTime),
          deadlineText: this.formatDeadline(homework.deadline),
          statusText: this.getStatusText(homework.deadline),
          statusClass: this.getStatusClass(homework.deadline),
          className: this.getClassName(homework.classId)
        };
      });
      
      console.log('处理后的作业数据:', processedHomework);
      
      this.setData({ 
        homeworkList: processedHomework,
        filteredHomework: processedHomework,
        loading: false 
      });
      
      // 应用当前筛选
      this.applyFilter();
    } catch (error) {
      console.error('获取作业列表失败:', error);
      console.error('错误详情:', JSON.stringify(error));
      this.setData({ 
        error: `加载失败: ${error.message || '未知错误'}`,
        loading: false 
      });
      
      wx.showModal({
        title: '加载失败',
        content: `错误信息: ${error.message || '未知错误'}`,
        showCancel: false
      });
    }
  },

  // 格式化时间
  formatTime(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前';
    }
    // 小于1天
    if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前';
    }
    // 小于7天
    if (diff < 604800000) {
      return Math.floor(diff / 86400000) + '天前';
    }
    
    // 超过7天显示具体日期
    return date.toLocaleDateString();
  },

  // 格式化截止时间
  formatDeadline(deadline) {
    if (!deadline) return '未设置';
    
    const date = new Date(deadline);
    const now = new Date();
    const diff = date - now;
    
    if (diff < 0) {
      return '已截止';
    } else if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟后截止';
    } else if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时后截止';
    } else {
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString().slice(0, 5);
    }
  },

  // 获取状态文本
  getStatusText(deadline) {
    if (!deadline) return '进行中';
    
    const date = new Date(deadline);
    const now = new Date();
    
    if (date < now) {
      return '已截止';
    } else {
      return '进行中';
    }
  },

  // 获取状态样式类
  getStatusClass(deadline) {
    if (!deadline) return 'active';
    
    const date = new Date(deadline);
    const now = new Date();
    
    if (date < now) {
      return 'expired';
    } else {
      return 'active';
    }
  },

  // 获取班级名称（这里需要根据实际情况实现）
  getClassName(classId) {
    // 这里应该根据classId查询班级名称
    // 暂时返回模拟数据
    const classNames = {
      1: '六年级(1)班',
      2: '六年级(2)班',
      3: '五年级(1)班'
    };
    return classNames[classId] || '未知班级';
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.applyFilter();
  },

  // 清除搜索
  clearSearch() {
    this.setData({ searchKeyword: '' });
    this.applyFilter();
  },

  // 筛选切换
  onFilterChange(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({ currentFilter: filter });
    this.applyFilter();
  },

  // 应用筛选
  applyFilter() {
    const { homeworkList, searchKeyword, currentFilter } = this.data;
    let filtered = [...homeworkList];

    // 搜索筛选
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(homework => 
        homework.title.toLowerCase().includes(keyword) ||
        homework.content.toLowerCase().includes(keyword)
      );
    }

    // 类型筛选
    if (currentFilter === 'active') {
      filtered = filtered.filter(homework => homework.statusClass === 'active');
    } else if (currentFilter === 'expired') {
      filtered = filtered.filter(homework => homework.statusClass === 'expired');
    } else if (currentFilter === 'my') {
      filtered = filtered.filter(homework => homework.publisherUserId === this.data.currentUserId);
    }

    // 按时间排序
    filtered.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));

    this.setData({ filteredHomework: filtered });
  },

  // 点击作业项
  onHomeworkTap(e) {
    const { homeworkId } = e.currentTarget.dataset;
    console.log('点击作业ID:', homeworkId);
    
    // 根据ID查找作业详情
    const homework = this.data.filteredHomework.find(h => h.homeworkId == homeworkId);
    if (homework) {
      wx.showModal({
        title: homework.title,
        content: `班级：${homework.className}\n截止时间：${homework.deadlineText}\n\n${homework.content}`,
        showCancel: false,
        confirmText: '知道了'
      });
    }
  },

  // 创建作业
  createHomework() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 编辑作业
  editHomework(e) {
    const { homework } = e.currentTarget.dataset;
    console.log('编辑作业:', homework);
    
    wx.showModal({
      title: '编辑作业',
      content: '编辑功能开发中',
      showCancel: false
    });
  },

  // 删除作业
  deleteHomework(e) {
    const { homework } = e.currentTarget.dataset;
    console.log('删除作业:', homework);
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个作业吗？',
      success: (res) => {
        if (res.confirm) {
          this.confirmDelete(homework);
        }
      }
    });
  },

  // 确认删除
  async confirmDelete(homework) {
    try {
      const result = await homeworkApi.deleteHomework(homework.homeworkId);
      if (result.success) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        // 重新加载数据
        this.loadHomework();
      } else {
        wx.showToast({
          title: result.message || '删除失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('删除作业失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  },

  // 查看统计
  viewStats(e) {
    const { homework } = e.currentTarget.dataset;
    console.log('查看统计:', homework);
    
    wx.showModal({
      title: '作业统计',
      content: '统计功能开发中',
      showCancel: false
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadHomework().then(() => {
      wx.stopPullDownRefresh();
    });
  }
});
